package com.bw.gmall.realtime.app.dwd;

import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class DwdToolCouponOrder {
    public static void main(String[] args) {
        //todo 初始化上下文  设置并行度
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);

        // TODO 3. 从 Kafka 读取业务数据，封装为 Flink SQL 表
        tenv.executeSql("create table `topic_db` (" +
                "`database` string, " +
                "`table` string, " +
                "`data`  map<string,string>, " +
                "`type` string, " +
                "`old` map<string,string>, " +
                "`ts` string " +
                ")"+ MyKafkaUtil.getKafkaDDL("topic_db","dwd_tool_coupon_order"));

        // TODO 4. 读取优惠券领用表数据，筛选满足条件的优惠券下单数据

        Table couponUse = tenv.sqlQuery("select " +
                "data['id'] id, " +
                "data['coupon_id'] coupon_id, " +
                "data['user_id'] user_id, " +
                "data['order_id'] order_id, " +
                "date_format(data['using_time'],'yyyy-MM-dd') date_id, " +
                "data['using_time'] using_time, " +
                "ts " +
                "from topic_db " +
                "where `table` = 'coupon_use' " +
                "and `type` = 'update' " +
                "and data['coupon_status'] = '1402' " +
                "and `old`['coupon_status'] = '1401' ");
        tenv.createTemporaryView("res_table",couponUse);

        // TODO 5. 建立 Kafka-Connector dwd_tool_coupon_order 表
        tenv.executeSql("create table dwd_tool_coupon_order(" +
                "id string, " +
                "coupon_id string, " +
                "user_id string, " +
                "order_id string, " +
                "date_id string, " +
                "order_time string, " +
                "ts string " +
                ")"+ MyKafkaUtil.getKafkaSinkDDL("dwd_tool_coupon_order"));

        tenv.executeSql("insert into dwd_tool_coupon_order select " +
                " id,  " +
                " coupon_id,  " +
                " user_id,  " +
                " order_id,  " +
                " date_id,  " +
                " using_time order_time,  " +
                " ts  " +
                "from res_table");
    }
}
